package net.lab1024.sa.admin.module.business.supercomputer.selectfilds.dao.selectdb;

import com.alibaba.fastjson.JSON;
import net.lab1024.sa.admin.module.business.supercomputer.selectfilds.dao.localdb.SelectFieldsInLocalDBDao;
import net.lab1024.sa.admin.module.business.supercomputer.selectfilds.domain.entity.ConnectionInfoEntity;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Mapper
@Repository
public class SelectFieldsInSelectDBDao {
    private Integer sourceId;
    private String url;

    @Resource
    private SelectFieldsInLocalDBDao selectFieldsInLocalDBDao;

    private Connection getConnection() throws Exception {
        String connectionInfoString = selectFieldsInLocalDBDao.getConnectionInfo(this.sourceId);

        ConnectionInfoEntity connectionInfo = JSON.parseObject(connectionInfoString, ConnectionInfoEntity.class);

        this.url = connectionInfo.getUrl();

        String url = connectionInfo.getUrl();
        String user = connectionInfo.getUsername();
        String password = connectionInfo.getPassword();

        return DriverManager.getConnection(url, user, password);
    }

    public List<Map<String, Object>> queryTable(String tableName, Integer sourceId) throws Exception {
        this.sourceId = sourceId;

        String sql = "SELECT * FROM " + tableName;

        try (Connection connection = getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(sql)) {

            ResultSet resultSet = preparedStatement.executeQuery();

            List<Map<String, Object>> resultList = new ArrayList<>();

            while (resultSet.next()) {
                Map<String, Object> row = new HashMap<>();

                int columnCount = resultSet.getMetaData().getColumnCount();

                for (int i = 1; i <= columnCount; i++) {
                    String columnName = resultSet.getMetaData().getColumnName(i);
                    Object columnValue = resultSet.getObject(i);

                    row.put(columnName, columnValue);
                }

                resultList.add(row);
            }

            return resultList;
        }
    }

    public List<Map<String, String>> queryTableColumn(String tableName) throws Exception {


        String sql = "SELECT column_name, data_type\n" +
                "FROM information_schema.columns\n" +
                "  WHERE table_name = ?";

        try (Connection connection = getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            preparedStatement.setString(1, tableName);
            ResultSet resultSet = preparedStatement.executeQuery();
            List<Map<String, String>> resultList = new ArrayList<>();

            while (resultSet.next()) {
                Map<String, String> columnInfo = new HashMap<>();
                columnInfo.put("column_name", resultSet.getString("column_name"));
                columnInfo.put("data_type", resultSet.getString("data_type"));
                resultList.add(columnInfo);
            }

            return resultList;
        }
    }

    public String queryTablePrimaryKey(String tableName) throws Exception {


        String sql = "SELECT column_name FROM information_schema.columns WHERE table_name = ? AND column_key = 'PRI'";

        try (Connection connection = getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            preparedStatement.setString(1, tableName);
            ResultSet resultSet = preparedStatement.executeQuery();

            if (resultSet.next()) {
                return resultSet.getString("column_name");
            } else {
                return null;
            }
        }
    }

    /**
     * 获取所有表名
     */
    public List<String> selectAllTable(Integer sourceId) throws Exception {
        this.sourceId = sourceId;


        List<String> tableNames = new ArrayList<>();
        try (Connection connection = getConnection();) {
            DatabaseMetaData metaData = connection.getMetaData();
            // 获取所有表名
            String url = this.url;
            String[] urls = url.split("/");
            String catalog = urls[3];
            System.out.println("catalog::"+catalog);

            ResultSet tables = metaData.getTables(catalog, null, "%", new String[]{"TABLE"});


            while (tables.next()) {
                String tableName = tables.getString("TABLE_NAME");
                tableNames.add(tableName);
                System.out.println("Table Name: " + tableNames);
            }
        }

        return tableNames;
    }
}
